package cn.ixinjiu.libraryMangement.controller.user.borrow;

import cn.ixinjiu.libraryMangement.entity.BorrowInfo;
import cn.ixinjiu.libraryMangement.entity.UserInfo;
import cn.ixinjiu.libraryMangement.service.IBorrowInfoService;
import cn.ixinjiu.libraryMangement.service.impl.BorrowInfoServiceImpl;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * Created by XinChen on 2023-05-12
 *
 * @TODO 借阅信息列表
 */
@WebServlet("/userBorrowsInfo")
public class BorrowInfoServlet extends HttpServlet {

    private IBorrowInfoService iBorrowInfoService = new BorrowInfoServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码格式
        req.setCharacterEncoding("utf-8");
        resp.setHeader("Content-Type", "text/html;charset=utf-8");

        // 登录时存入的用户数据 -> 详见 "LoginServlet"
        UserInfo userInfo = (UserInfo) req.getSession().getAttribute("userInfo");
        List<BorrowInfo> borrowInfos = iBorrowInfoService.getBorrowsInfoByUserId(userInfo.getId());
        JSONArray jsonArray = new JSONArray(); // 中转站
        JSONObject jsonObject = new JSONObject(); // 要返回的json对象


        for (BorrowInfo borrowInfo : borrowInfos) {
            JSONObject jsonData = new JSONObject(); // json数据
            jsonData.put("id", borrowInfo.getId());
            jsonData.put("userId", borrowInfo.getUserId());
            jsonData.put("bookId", borrowInfo.getBookId());
            jsonData.put("borrowDate", borrowInfo.getBorrowDate());
            jsonData.put("returnDate", borrowInfo.getReturnDate());
            jsonData.put("actualReturn", borrowInfo.getActualReturn());
            jsonData.put("isReturned", borrowInfo.getIsReturned());
            jsonData.put("isOverdue", borrowInfo.getIsOverdue());
            jsonData.put("overdueDays", borrowInfo.getOverdueDays());
            jsonArray.add(jsonData);
        }


        // 数据总数
        int count = iBorrowInfoService.count();

        jsonObject.put("code", 0); // 设置状态码，0正常
        jsonObject.put("data", jsonArray.toArray()); // 设置数据
        jsonObject.put("count", count); // 设置 “共 ？ 条” 数据
        jsonObject.put("msg", "success~"); // 设置提示信息
        // 写入到页面
        PrintWriter out = resp.getWriter();
        out.write(jsonObject.toString());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
